package com.whosly.strategy.scan.spring;

import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ClassUtils;

import java.io.IOException;

/**
 * @Author yueny09 <deep_blue_yang@126.com>
 * @Date 2019-09-05 16:46
 */
public class StrategyContainerTypeFilter implements TypeFilter {

    private Class<?> targetType;

    public StrategyContainerTypeFilter(Class<?> targetType) {
        this.targetType = targetType;
    }

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        if(!metadataReader.getClassMetadata().isInterface()) {
            return false;
        }

        // 取得目标类的所有接口，只要目标类实现了targetType就返回true
        String[] interfaceNames = metadataReader.getClassMetadata().getInterfaceNames();
        for (String interfaceName : interfaceNames) {
            if (!targetType.getName().equals(interfaceName)) {
                return false;
            }

            try {
                Class<?> clazz = ClassUtils.forName(interfaceName, getClass().getClassLoader());
                if(!this.targetType.isAssignableFrom(clazz)){
                    return false;
                }

//                // 标了注解
//                if(clazz.isAnnotationPresent(this.annotation)){
                    return true;
//                }
            } catch (Throwable ex) {
                // Class not regularly loadable - can't determine a match that way.
            }
        }
        return false;
    }
}
